package main

import (
	"context"
	"github.com/apache/dubbo-go/config"
	"gopkg.in/mgo.v2/bson"
	"jkgo/jk/jklog"
	"jkgo/jkdbs"
)

var globalDBS *jkdbs.Mongo

func init() {
	config.SetProviderService(new(UserProvider))
	// ------for hessian2------
	globalDBS = jkdbs.NewMongo("mongodb://jmduser:jmduser321@127.0.0.1/user")
}

type UserProvider struct {
}

func (u *UserProvider) AddOne(ctx context.Context, user *User) (*User, error) {
	jklog.L().Infoln("do add user ", user.Name)
	err := globalDBS.Add("user", "baseinfo", user)
	if err != nil {
		jklog.L().Errorln(err)
		return nil, err
	}
	return user, nil
}

func (u *UserProvider) RmOne(ctx context.Context, user *User) error {
	jklog.L().Infoln("do del user ", user.Name)
	find := bson.M{"Name": user.Name}
	_, err := globalDBS.Cnew("user", "baseinfo").RemoveAll(find)
	return err
}

func (u *UserProvider) FindOne(ctx context.Context, name string) (*User, error) {
	jklog.L().Infoln("find user ", name)
	findUser := bson.M{"Name": name}
	user := User{}
	r := globalDBS.Cnew("user", "baseinfo").Find(&findUser).One(&user)
	if r != nil {
		return nil, r
	}
	return &user, nil
}

func (u *UserProvider) Reference() string {
	return "UserProvider"
}
